package com.wx.chapter17.homework;

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author : 佩萁
 * Description :
 * @Create : 2023/8/21 - 16:15
 */
public class Homework01 {
    public static void main(String[] args) {
        A a = new A();
        B b = new B(a);
        a.start();
        b.start();
    }
}

class A extends Thread {
    private boolean loop = true;

    public void setLoop(boolean loop) {
        this.loop = loop;
    }

    @Override
    public void run() {
        //输出1-100数字
        while (loop) {
            System.out.println((int) (Math.random() * 100 + 1));
            //休眠
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("a线程退出");
    }
}

class B extends Thread {
    private A a;
    private Scanner scanner = new Scanner(System.in);

    public B(A a) {//这里需要传入被通知的线程，如果不传，我们也可以对A进行一些操作，但是这是否是同一个A线程呢？肯定不是
        this.a = a;
    }

    @Override
    public void run() {
        while (true) {
            //接收用户的输入
            System.out.println("请输入指令,Q表示退出");
            char key = scanner.next().toUpperCase().charAt(0);
            if (key == 'Q') {
                //以通知的方式结束a线程
                a.setLoop(false);
                System.out.println("b线程结束.");
                break;
            }
        }
    }
}